package sku

import (
	"context"
	"mall/common/excption"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QuerySkuInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQuerySkuInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuerySkuInfoLogic {
	return &QuerySkuInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QuerySkuInfoLogic) QuerySkuInfo(in *pb.QuerySkuInfoDTO) (*pb.QuerySkuInfoVO, error) {
	// 1.query sku info
	skuMapper := mapper.NewSkuMapper()
	skuInfoDO, err := skuMapper.SelectSkuListBySkuId(l.ctx, l.svcCtx.DBEngin, in.SkuId)
	if err != nil {
		return nil, err
	}
	if skuInfoDO.SkuId <= 0 {
		return nil, excption.NewErrCode(constans.SkuIsDeletedError)
	}
	// 2.query sku attr
	skuAttrValueMapper := mapper.NewSpuSkuAttrValueMapper()
	skuAttrValueBO := bo.SpuSkuAttrValueBO{SkuId: in.SkuId}
	selectListCtx, err := skuAttrValueMapper.SelectListCtx(l.ctx, l.svcCtx.DBEngin, skuAttrValueBO)
	if err != nil {
		return nil, err
	}
	// 3.package obj
	if len(selectListCtx) <= 0 {
		return &pb.QuerySkuInfoVO{}, nil
	}
	// 3.1 sku info
	resp := new(pb.QuerySkuInfoVO)
	resp.SkuId = skuInfoDO.SkuId
	resp.SkuName = skuInfoDO.SkuName
	resp.Attrs = skuInfoDO.Attrs
	resp.ImgUrl = skuInfoDO.ImgUrl
	resp.PriceFee = skuInfoDO.PriceFee
	resp.MarketPriceFee = skuInfoDO.MarketPriceFee
	resp.PartyCode = skuInfoDO.PartyCode
	resp.ModelId = skuInfoDO.ModelId
	resp.Weight = float32(skuInfoDO.Weight)
	resp.Volume = float32(skuInfoDO.Volume)
	resp.Stock = int32(skuInfoDO.ActualStock)
	resp.TotalStock = int32(skuInfoDO.Stock)
	// 3.2 sku attr
	var attValueArr []*pb.SpuSkuAttrValueVO
	for _, v := range selectListCtx {
		skuAttr := pb.SpuSkuAttrValueVO{}
		skuAttr.SpuSkuAttrValueId = v.SpuSkuAttrId
		skuAttr.AttrId = v.AttrId
		skuAttr.AttrName = v.AttrName
		skuAttr.AttrValueId = v.AttrValueId
		skuAttr.AttrValueName = v.AttrValueName
		attValueArr = append(attValueArr, &skuAttr)
	}
	resp.SpuSkuAttrValues = attValueArr
	return resp, nil
}
